package com.omp.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;
import org.springside.modules.orm.Page;

import com.omp.common.dao.BaseDAO;
import com.omp.dao.ProductDAO;
import com.omp.entity.Product;

@Repository
public class ProductDAOImpl extends BaseDAO<Product, Integer> implements ProductDAO {

	@Override
	public Page<Product> findByPage(Page<Product> page, Product product) {
		StringBuilder hql = new StringBuilder("from Product where 1=1");
		Map<String, Object> params = new HashMap<String, Object>();
		if (product != null) {
			if (StringUtils.isNotBlank(product.getName())) {
				hql.append(" and name like :name");
				params.put("name", "%" + product.getName() + "%");
			}
		}
		return findPage(page, hql.toString(), params);
	}

	@Override
	public boolean nameExists(String name) {
		String hql = "select count(id) from Product where name=?";
		return ((Long)findUnique(hql, name)) > 0;
	}

	@Override
	public void deleteById(Integer id) {
		String hql = "delete Product where id=?";
		batchExecute(hql, id);
	}

	@Override
	public List<Product> findByIndustryId(Integer industryId, Product product) {
		return findByIndustryId(industryId, product, false);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> findByIndustryId(Integer industryId, Product product, boolean findNoneIndustry) {
		StringBuilder hql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();
		if (findNoneIndustry) {
			hql.append("select p.* from base_product_list p,busi_product_catalog pc where p.product_id=pc.product_id and pc.industry_id=:industryId union select p.* from base_product_list p where not exists (select product_id from busi_product_catalog pc where pc.product_id=p.product_id)");
		} else {
			hql.append("select p.* from base_product_list p,busi_product_catalog pc where p.product_id=pc.product_id and pc.industry_id=:industryId");
		}
		params.put("industryId", industryId);
		if (product != null) {
			if (StringUtils.isNotBlank(product.getName())) {
				hql.append(" and p.product_name like :name");
				params.put("name", "%" + product.getName() + "%");
			}
		}
		SQLQuery query = getSession().createSQLQuery(hql.toString()).addEntity(Product.class);
		query.setProperties(params);
		return query.list();
	}

}
